<template>
  <el-card>
    <div class="DHeader">
      <el-form :model="Dform" ref="Dform" @submit.prevent>
        <span
          style="
            font-size: 20px;
            font-weight: 600;
            height: 7vh;
            line-height: 7vh;
            margin-left: 50px;
          "
          >医务室药品管理</span
        >
        <el-row
          :gutter="28"
          style="width: 50vw; padding-top: 9px; height: 7vh; float: right"
        >
          <el-col :span="8">
            <el-form-item style="float: right">
              <span style="font-size: 18px">&nbsp;</span>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="drugname">
              <el-input
                placeholder="输入药品名称"
                v-model="Dform.drugname"
                @change="SelectDrugs"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item>
              <el-button type="primary" @click="SelectDrugs">查询</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item>
              <el-button type="primary" @click="addDrugs">新增</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="DContent">
      <el-table
        :data="
          DrugsList.slice((currentPage - 1) * pageSize, currentPage * pageSize)
        "
        border
        id="eltable"
        height="61vh"
        :header-cell-style="{ 'text-align': 'center', 'font-size': '14px' }"
        :cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column prop="did" fixed label="药品编号" />
        <el-table-column prop="dname" fixed label="药品名称" />
        <el-table-column prop="dbrand" fixed label="药品品牌" />
        <el-table-column prop="dproduct" fixed label="生产厂家" width="220" />
        <el-table-column prop="dcreate" fixed label="生产日期" />
        <el-table-column prop="dendtime" fixed label="有效期至" />
        <el-table-column prop="dprice" fixed label="价格(元)" />
        <el-table-column prop="stock" fixed label="库存量">
          <template #default="props">
            <el-tooltip
              class="item"
              effect="dark"
              :content="props.row.stock"
              placement="top-start"
            >
              <span :class="[props.row.stock < 300 ? 'red' : 'black']">{{
                props.row.stock < 300 ? "余量不足300" : props.row.stock
              }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="dnorm" fixed label="规格" />
        <el-table-column prop="name" label="操作" width="220">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="ApplyDrugs(scope.row.did)"
            >
              {{ scope.row.status == 0 ? "申请" : "待审核" }}
            </el-button>
            <el-button
              link
              size="small"
              type="primary"
              @click="ADDinDrugs(scope.row.did)"
              >入库</el-button
            >
            <el-button
              link
              size="small"
              type="primary"
              @click="EditDrugs(scope.row.did)"
              >修改</el-button
            >
          </template>
        </el-table-column>
        <template v-slot:empty>
          <span style="color: #969799">未查询到药品信息</span>
        </template>
      </el-table>
      <div class="page">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          background
          :total="DrugsList.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="DialogEditDrug"
      title="药品信息编辑"
      style="width: 450px"
    >
      <el-form :model="EDrug" ref="edrug" :rules="rules" class="DialogEditDrug">
        <el-form-item label="药品名称" prop="dname">
          <el-input v-model="EDrug.dname" />
        </el-form-item>
        <el-form-item label="药品品牌" prop="dbrand">
          <el-input v-model="EDrug.dbrand" />
        </el-form-item>
        <el-form-item label="生产厂家" prop="dproduct">
          <el-input v-model="EDrug.dproduct" />
        </el-form-item>

        <el-form-item label="药品价格" prop="dprice">
          <el-input v-model="EDrug.dprice" />
        </el-form-item>
        <el-form-item label="规格" prop="dnorm">
          <el-input v-model="EDrug.dnorm" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="DialogEditDrug = false">关闭</el-button>
          <el-button type="primary" @click="SaveDrugs()"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增药品种类 -->
    <el-dialog
      v-model="DialogDrugAdd"
      title="新增药品信息"
      style="width: 450px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form
        :model="addPramas"
        ref="addPramas"
        :rules="rules"
        class="DialogDrugAdd"
      >
        <el-form-item label="药品名称" prop="dname">
          <el-input v-model="addPramas.dname" />
        </el-form-item>
        <el-form-item label="药品品牌" prop="dbrand">
          <el-input v-model="addPramas.dbrand" />
        </el-form-item>
        <el-form-item label="生产厂家" prop="dproduct">
          <el-input v-model="addPramas.dproduct" />
        </el-form-item>
        <el-form-item label="生产日期" prop="dcreate">
          <el-date-picker
            v-model="addPramas.dcreate"
            type="date"
            format="YYYY-MM-DD"
            value-format="x"
          />
        </el-form-item>
        <el-form-item label="有效期至" prop="dendtime">
          <el-date-picker
            v-model="addPramas.dendtime"
            type="date"
            format="YYYY-MM-DD"
            value-format="x"
          />
        </el-form-item>
        <el-form-item label="药品价格" prop="dprice">
          <el-input v-model="addPramas.dprice" />
        </el-form-item>
        <el-form-item label="初始库存" prop="stock">
          <el-input v-model="addPramas.stock" />
        </el-form-item>
        <el-form-item label="药品规格" prop="dnorm">
          <el-input v-model="addPramas.dnorm" />
        </el-form-item>
        <el-form-item label="药品来源" prop="dfrom">
          <el-input v-model="addPramas.dfrom" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog()">关闭</el-button>
          <el-button type="primary" @click="addDrugsSaving()"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>
<script>
import {
  queryDrugsList,
  queryDrugByName,
  UpdateDrug,
  applyDrug,
  applyRefused,
  addDrugs,
} from "@/api/drugs";
import { FindInfo } from "@/api/login.js";
import { pageMixin } from "@/mixins/pageMixin";
import { ElMessage, ElMessageBox } from "element-plus";
// import { tr } from "element-plus/es/locale";
export default {
  mixins: [pageMixin],
  data() {
    return {
      addPramas: {},
      submitParams: {},
      DialogDrugAdd: false,
      DialogEditDrug: false,
      Dform: {
        drugname: "",
      },
      DrugsList: [],
      ComputedDrug: {
        did: null,
        dname: null,
        dbrand: null,
        dproduct: null,
        dcreate: null,
        dendtime: null,
        dprice: null,
        stock: null,
        used: null,
        addin: null,
        addstaff: null,
        dfrom: null,
        dnorm: null,
      },
      EDrug: {
        did: null,
        dname: "",
        dbrand: "",
        dproduct: "",
        dcreate: "",
        dendtime: "",
        dprice: "",
        stock: 0,
        used: 0,
        addin: 0,
        addstaff: "",
        dfrom: "",
      },
      rules: {
        dprice: [
          {
            required: true,
            message: "请输入金额",
            pattern: /^-?\d{1,3}(,\d{3})*(\.\d{1,2})?$/,
            trigger: "blur",
          },
        ],
        dname: [
          {
            required: true,
            message: "请输入药品名称",
            trigger: "blur",
          },
        ],
        dfrom: [
          {
            required: true,
            message: "请输入药品来源",
            trigger: "blur",
          },
        ],
        stock: [
          {
            required: true,
            message: "请输入初始库存",
            trigger: "blur",
          },
        ],

        dcreate: [
          {
            required: true,
            message: "请选择生产日期",
            trigger: "blur",
          },
        ],
        dendtime: [
          {
            required: true,
            message: "请选择有效期至",
            trigger: "blur",
          },
        ],
        dbrand: [
          {
            required: true,
            message: "请输入药品品牌",
            trigger: "blur",
          },
        ],
        dproduct: [
          {
            required: true,
            message: "请输入生产厂家",
            trigger: "blur",
          },
        ],
        dnorm: [
          {
            required: true,
            message: "请输入药品规格",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.fetchDrugs();
    this.username = localStorage.getItem("username");
    FindInfo(this.username).then((res) => {
      this.address = res.data.data.address;
      this.name = res.data.data.name;
    });
  },
  methods: {
    fetchDrugs() {
      queryDrugsList().then((res) => {
        this.DrugsList = res.data.data;
        res.data.data.forEach((item) => {
          if (item.status == 2) {
            ElMessageBox.confirm(item.dname + "：" + item.msg, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "关闭",
              type: "warning",
            }).then(() => {
              this.submitParams.did = item.did;
              this.submitParams.msg = item.msg;
              this.submitParams.status = 0;
              applyRefused(this.submitParams).then((res) => {
                this.fetchDrugs();
              });
            });
          }
        });
      });
    },
    SelectDrugs() {
      if (this.Dform.drugname == "") {
        this.fetchDrugs();
      } else {
        queryDrugByName(this.Dform.drugname).then((res) => {
          this.DrugsList = res.data.data;
        });
      }
    },
    FindDrug(did) {
      for (var i = 0; i < this.DrugsList.length; i++) {
        if (did == this.DrugsList[i].did) {
          this.ComputedDrug = this.DrugsList[i];
          break;
        }
      }
    },
    ApplyDrugs(did) {
      this.FindDrug(did);
      console.log(this.ComputedDrug);
      if (this.ComputedDrug.status == 0) {
        ElMessageBox.prompt("请输入申请数量", "Tip", {
          confirmButtonText: "申请",
          cancelButtonText: "关闭",
          inputPattern: /^\d+$/,
          inputErrorMessage: "不合法的数量",
        })
          .then(({ value }) => {
            ElMessage({
              type: "success",
              message: `编号${did}的申请数量为:${value}`,
            });
            this.submitParams.did = did;
            this.submitParams.addin = value;
            this.submitParams.addstaff = this.name;
            this.submitParams.applyaddress = this.address;
            return applyDrug(this.submitParams);
          })
          .then(() => {
            this.fetchDrugs();
          })
          .catch(() => {
            ElMessage({
              type: "info",
              message: "取消成功",
            });
          });
      } else {
        ElMessageBox.alert("您已申请该药品，请等待管理员审核", "提示", {
          confirmButtonText: "确定",
          type: "warning",
        });
      }
    },
    ADDinDrugs(did) {
      this.FindDrug(did);
      ElMessageBox.prompt("请输入编号" + did + "药品的入库数量", "Tip", {
        confirmButtonText: "入库",
        cancelButtonText: "关闭",
        inputPattern: /^\d+$/,
        inputErrorMessage: "不合法的数量",
      })
        .then(({ value }) => {
          ElMessage({
            type: "success",
            message: `编号${did}的药品入库数量为:${value}`,
          });
          this.ComputedDrug.did = did;
          this.ComputedDrug.addin = parseInt(value);
          this.ComputedDrug.stock =
            parseInt(this.ComputedDrug.stock) +
            parseInt(this.ComputedDrug.addin);
          return UpdateDrug(this.ComputedDrug);
        })
        .then(() => {
          this.fetchDrugs();
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "取消入库",
          });
        });
    },
    SaveDrugs() {
      ElMessageBox.confirm("确认修改药品信息?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "关闭",
        type: "warning",
      })
        .then(() => {
          ElMessage({
            type: "success",
            message: "修改成功",
          });
          this.DialogEditDrug = false;
          return UpdateDrug(this.EDrug);
        })
        .then(() => {
          this.fetchDrugs();
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "取消成功",
          });
        });
    },
    EditDrugs(did) {
      this.DialogEditDrug = true;
      this.FindDrug(did);
      this.EDrug = this.ComputedDrug;
    },
    addDrugs() {
      this.DialogDrugAdd = true;
    },
    addDrugsSaving() {
      this.$refs.addPramas.validate((valid) => {
        if (valid) {
          this.addPramas.addstaff = this.name;
          addDrugs(this.addPramas).then(() => {
            ElMessage({
              type: "success",
              message: "添加成功",
            });
            this.fetchDrugs();
            this.closeDialog();
          });
        }
      });
    },
    closeDialog() {
      this.$refs.addPramas.clearValidate();
      this.DialogDrugAdd = false;
      this.addPramas = {};
    },
  },
};
</script>
<style>
.DHeader {
  width: 100%;
  height: 7vh;
  margin-bottom: 5px;
}

.DContent {
  width: 100%;
  height: 67vh;
}

.page {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-right: 20px;
  align-items: end;
  width: 100%;
  height: 40px;
  background-color: white;
}

.DialogEditDrug .el-form-item__label {
  width: 125px !important;
}

.DialogEditDrug .el-input {
  width: 200px;
}
.DialogDrugAdd .el-form-item__label {
  width: 125px !important;
}

.DialogDrugAdd .el-input {
  width: 200px;
}
.red {
  color: red;
  font-weight: 600;
}
</style>
